
import 'package:erp/Entity/ProductInWareHouse.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/AccountStore.dart';
import 'package:erp/Store/ProductsInWareHouseStore.dart';
import 'package:erp/global.dart';

void registerWareHouseManagementEvents(){

  globalBus.subscribe(Events.PRODUCT_IN_WAREHOUSE_SELECT_REQUEST, (bus, _)async {
    try {
      var result = await externalInterface.getAllProductsInWareHouse(AccountStore.signInResult.token);
      ProductsInWareHouseStore.products = result;
      bus.publish(Events.PRODUCT_IN_WAREHOUSE_SELECT_SUCCESS, result);
    }
    catch (exception){
      bus.publish(Events.PRODUCT_IN_WAREHOUSE_SELECT_ERROR, exception);
    }
  });

  globalBus.subscribe<ProductInWareHouse>(Events.PRODUCT_IN_WAREHOUSE_EDIT_REQUEST, (bus, product) async {
    try {
      var data = await externalInterface.editProductInWareHouse(AccountStore.signInResult.token, product);
      ProductsInWareHouseStore.products.singleWhere((item) => product.id == item.id)
        ..comment = data.comment
        ..oldBalanceCount = data.oldBalanceCount
        ..balanceCount = data.balanceCount;

      bus.publish(Events.PRODUCT_IN_WAREHOUSE_EDIT_SUCCESS, data);
    }
    catch (exception){
      bus.publish(Events.PRODUCT_IN_WAREHOUSE_EDIT_ERROR, exception);
    }
  });

  globalBus.subscribe<ProductInWareHouse>(Events.PRODUCT_IN_WAREHOUSE_DELETE_REQUEST, (bus, product) async {
    try {
      var data = await externalInterface.deleteProductInWareHouse(AccountStore.signInResult.token, product);
      ProductsInWareHouseStore.products.removeWhere((item) => item.id == data.id);
      bus.publish(Events.PRODUCT_IN_WAREHOUSE_DELETE_SUCCESS, data);
    }
    catch (exception){
      bus.publish(Events.PRODUCT_IN_WAREHOUSE_DELETE_ERROR, exception);
    }
  });
  
  globalBus.subscribe<ProductInWareHouse>(Events.PRODUCT_IN_WAREHOUSE_EDIT_PRICE_REQUEST, (bus, product) async {
    try {
      var data = await externalInterface.editPriceOfProductInWareHouse(AccountStore.signInResult.token, product);

      ProductsInWareHouseStore.products.singleWhere((item) => product.id == item.id)
        ..attach = data.attach;

      bus.publish(Events.PRODUCT_IN_WAREHOUSE_EDIT_PRICE_SUCCESS, data);
    }
    catch (exception) {
      bus.publish(Events.PRODUCT_IN_WAREHOUSE_EDIT_PRICE_ERROR, exception);
    }
  });
}

